angular.module('CheckWork')

.controller('CheckWork.HomeCtrl', ['$scope', '$state', 'CheckWorkHomeService', 'User','Device', 'imanDialog', '$ionicLoading', 'imanUsbPort', '$ionicModal', function($scope, $state, CheckWorkHomeService, User,Device, imanDialog, $ionicLoading, imanUsbPort, $ionicModal) {
    // var uuid = '00:11:22:33'; // 设备标识
    var Barcode = '695676DB'; // 条码标识
    var BarcodeId = 0;
    var bizRecordId = 0;//流水id
    var userId = User.get("_id");//用户id
    var deviceId = Device.get("Terminal")._id;
    var deviceName = Device.get("Terminal").Name;
    var workId = Device.get("Work")._id;
    var workName = Device.get("Work").Name;
    var WorkLocationId = Device.get("WorkLocation")._id;
    var WorkLocationName = Device.get("WorkLocation").Name;
    var addFlag = true;//增加还是修改标志位
    //0: 合格 1:不合格 
    var QCStatus = 0;
    //不良位置
    $scope.position = [];
    //存储不良缺陷信息
    var listData = {};
    //存储不良缺陷选中信息
    var listCheck = null;
    var listDefect = null;
    // $scope.defectList = {
    //     'B': ['补漆不良', '柄皮污染'],
    //     'C': ['尺寸标不良'],
    //     'D': ['底盖外协/破损', '断拍'],
    //     'J': ['胶水污染', '金油污染'],
    //     'K': ['孔边掉漆', '孔径不良', '孔距不良'],
    //     'L': ['离膜未净', '镭射标不良', '裂漆'],
    //     'P': ['碰伤/划伤', 'PU未饱和', 'PU发泡', 'PU补土不良', 'PU落差', 'PU错位', 'PU外泄'],
    //     'Q': ['清洁度不良'],
    //     'S': ['水标破残', '水标错/漏'],
    //     'T': ['条护破损', '条护毛边', '条护不密合', '涂装不良'],
    //     'Z': ['粘碳片不密合', '装配污染']
    // };
    $scope.queryStr = '';
    //不良缺陷
    $scope.defectList = {};
    $scope.data = {
        work_id: '',
        one: {},
        badRecords: []
        

            // qcRecords: [{
            //     BadPosition: "内12点",
            //     BadType: "碰伤/划伤",
            //     Description: "轻微划伤",
            //     Images: []
            // }, {
            //     BadPosition: "2/10点",
            //     BadType: "孔边掉漆",
            //     Description: "面积不大",
            //     Images: []
            // }]
    };

    $scope.pushDefect = function(type) {
        $scope.data.badRecords.push({
            BadType: type.name,
            BadTypeValue: type.value,
            BadPosition: "",
            BadPositionValue: 0,
            Description: ""
            
        });
    };
    $scope.popDefect = function(type) {
        for (var i = 0; i < $scope.data.badRecords.length; i++) {
            if ($scope.data.badRecords[i].name === type) {
                $scope.data.badRecords.splice(i, 1);
                break;
            }
        }
    };

    $scope.onBadPos = function (defect) {
        imanDialog.showLoading();
        CheckWorkHomeService.getBadPositionList("BadPosition").then(function(data) {
            imanDialog.hideLoading();
            if (data != null) {
                $scope.position = [];
                for(var i in data){
                    $scope.position.push({id:i,name:data[i]});
                }
                imanDialog.showList({
                    title: '请选择碰伤/划伤位置',
                    list: $scope.position,
                    valueField: 'id',
                    displayField: 'name',
                    value: defect.BadPositionValue
                }).then(function (select) {
                    defect.BadPositionValue = select.id;
                    defect.BadPosition = select.name;
                });
            } else {
                imanDialog.alert("数据为空", "");
            }
        }, function(error) {
            imanDialog.hideLoading();
            
        });

        
    };
    function getBarcodeDefaultInfo() {
        
        imanDialog.showLoading();
        CheckWorkHomeService.getBarcodeData(Barcode).then(function(barcodedata) {
            
            if (barcodedata != null) {
                 //要修改缺陷信息
                if(workId === barcodedata.Work){
                   imanDialog.alert("请修改缺陷信息", "");
                   addFlag = false; 
                   BarcodeId = barcodedata._id;
                   CheckWorkHomeService.getBarcodeDefectData(BarcodeId,workId).then(function(defectdata){
                     imanDialog.hideLoading();
                     $scope.data.one = barcodedata;
                     $scope.data.badRecords = defectdata;
                     bizRecordId = defectdata[0].BizRecord;

                   },function(eror){
                     imanDialog.hideLoading();
                   });
                }
                //要增加缺陷信息
                else{
                   imanDialog.alert("请增加缺陷信息", "");
                   addFlag = true; 
                   imanDialog.hideLoading();
                   $scope.data.one = barcodedata;
                }
                
            } else {
                imanDialog.hideLoading();
                imanDialog.alert("单品数据为空", "");
            }
            
        }, function(error) {
            imanDialog.hideLoading();
        });

    }

    // getBarcodeDefaultInfo();

    $ionicModal.fromTemplateUrl(u9ImHd.getFullPath('tpls/defectModal.html', 'CheckWork'), {
        scope: $scope,
        animation: 'slide-in-up'
    }).then(function(modal) {
        $scope.modal = modal;
    });
    $scope.openModal = function() {
        $scope.modal.show();
        imanDialog.showLoading();
        CheckWorkHomeService.getBadTypeList($scope.data.one.ItemMaster, workId).then(function(data) {
            imanDialog.hideLoading();
            $scope.defectList = {};
            var pinyin = '';
            var pinyinTop = '';
            var name = '';
            var value = 0;
            if (data != null) {
                for (var i = 0; i < data.length; i++) {
                    name = data[i].Name;
                    value = data[i].Value;
                    pinyin = makePy(name)[0].toLowerCase();
                    pinyinTop = pinyin.charAt(0);
                    
                    if ($scope.defectList[pinyinTop]) {
                        $scope.defectList[pinyinTop].push({name:name,value:value,pinyin:pinyin,check:false});
                    } else {
                        $scope.defectList[pinyinTop] = [{name:name,value:value,pinyin:pinyin,check:false}];
                    }
                }
                listData = $scope.defectList;
                //增加
                if(addFlag){
                    if(listCheck){
                        for (var k in listCheck) {      
                           var pinyinTopList = listCheck[k];
                           for (var j = 0; j < pinyinTopList.length; j++) {
                               for (var a in listData) {      
                                   var pinyinList = listData[a];
                                   for (var b = 0; b < pinyinList.length; b++) {
                                       if(pinyinTopList[j].value === pinyinList[b].value){
                                          listData[a][b].check = listCheck[k][j].check;
                                       }
                                   }
                                }
                           }
                        }
                    }
                    else{
                        listCheck = $scope.defectList;
                    }
                }
                //编辑
                else{
                         
                       
                       for (var p = 0; p < $scope.data.badRecords.length; p++) {
                           for (var m in listData) {      
                               var pinyinList2 = listData[m];
                               for (var n = 0; n < pinyinList2.length; n++) {
                                   if($scope.data.badRecords[p].BadTypeValue === pinyinList2[n].value){
                                      listData[m][n].check = true;
                                   }
                               }
                            }
                       }
                       listCheck = listData;
                    
                }
                
            } else {
                imanDialog.alert("缺陷信息为空", "");
            }
        
        }, function(error) {
            imanDialog.hideLoading();
            $scope.data = {};
        });

    };
    $scope.closeModal = function() {
        $scope.modal.hide();
        
    };

    // function getBarCodeData(code) {
    //     imanDialog.showLoading();
    //     CheckWorkHomeService.getQCDefaultInfoData(code, $scope.data.work_id).then(function(data) {
    //         imanDialog.hideLoading();
    //         if (data != null) {
    //             $scope.data = data;
    //         } else {
    //             imanDialog.alert("单品数据为空", "");
    //         }
    //     }, function(error) {
    //         imanDialog.hideLoading();
    //         $scope.data = {};
    //     });
    // }

    $scope.submitData = function() {
        
        imanDialog.showLoading();
        if(addFlag){
            QCStatus = $scope.data.badRecords.length>0 ? 1 : 0;
            CheckWorkHomeService.submitBadData(Barcode,$scope.data.one._id,$scope.data.one.ItemMaster,deviceId,deviceName,workId,workName,WorkLocationId,WorkLocationName,userId,QCStatus,$scope.data.badRecords).then(function(data) {
                imanDialog.hideLoading();
                if (data) {
                    imanDialog.alert("全检成功", "");
                } else {
                    imanDialog.alert("全检失败", "");
                }
            }, function(res) {
                imanDialog.hideLoading();
            });
        }
        else{
            CheckWorkHomeService.updateBadData(bizRecordId,BarcodeId,Barcode,userId,$scope.data.badRecords).then(function(data){
                imanDialog.hideLoading();
                if (data) {
                    imanDialog.alert("更新全检数据成功", "");
                } else {
                    imanDialog.alert("更新全检数据失败", "");
                }
            },function(error){
                imanDialog.hideLoading();
            });
        }
        
    };
    
    // 保存选中记录
    $scope.checkChange = function(one) {
        for (var a in listCheck) {      
           var pinyinList = listCheck[a];
           for (var b = 0; b < pinyinList.length; b++) {
               if(one.value === pinyinList[b].value){
                  listCheck[a][b].check = one.check;
               }
           }
        }
        
        if(one.check){
            $scope.data.badRecords.push({
            BadType: one.name,
            BadTypeValue: one.value,
            BadPosition: "",
            BadPositionValue: 0,
            Description: ""
            
           });
        }
        else{
            for (var i = 0; i < $scope.data.badRecords.length; i++) {
                if ($scope.data.badRecords[i].BadTypeValue === one.value) {
                    $scope.data.badRecords.splice(i, 1);
                    break;
                }
            }
        }      
    };

    $scope.search = function(query) {

        if (query === "") {
            $scope.defectList = listCheck;
        }
        if (query !== "") {
            var nName;
            var nPinyin;
            $scope.defectList = {};

            for (var i in listData) {      
                var pinyinTopList = listData[i];
                for (var j = 0; j < pinyinTopList.length; j++) {
                    var item = pinyinTopList[j];
                    var pinyin = item.pinyin;
                    var name = item.name;
                    nName = find(query, name);
                    nPinyin = find(query, pinyin);
                    if (nName >= 0 || nPinyin >= 0) {
                        if ($scope.defectList[i]) {
                            $scope.defectList[i].push({name:item.name,value:item.value,pinyin:item.pinyin,check:item.check});
                        } else {
                            $scope.defectList[i] = [{name:item.name,value:item.value,pinyin:item.pinyin,check:item.check}];
                        }
                    }
                    
                }  
            }
            
        }
        
    };

    function find(sFind, sObj) {
        var nSize = sFind.length;
        var nLen = sObj.length;
        var sCompare;

        if (nSize <= nLen) {
            for (var i = 0; i <= nLen - nSize + 1; i++) {
                sCompare = sObj.substring(i, i + nSize);
                if (sCompare === sFind) {
                    return i;
                }
            }
        }
        return -1;
    }

    $scope.$on('$ionicView.beforeEnter', function() {
        imanUsbPort.start();
    });
    $scope.$on('$ionicView.afterLeave', function() {
        imanUsbPort.stop();
    });
    $scope.$on('imanUsbPort.input', function(e, inputStr) {
        imanDialog.toastBottom(inputStr);
        Barcode = inputStr;
        
        getBarcodeDefaultInfo();
    });
        //当我们用到模型时，清除它！
      $scope.$on('$destroy', function() {
        $scope.modal.remove();
      });
      // 当隐藏的模型时执行动作
      $scope.$on('modal.hide', function() {
        // 执行动作
        $scope.queryStr = '';
      });
}]);